using System;
using System.Linq;
using System.Collections.Generic;
using DevExpress.CodeRush.StructuralParser;
using CR.StyleCop.Extensions;

namespace CR.StyleCop.Naming {

    public class FieldNamesMustBeginWithLowerCaseLetterSearcher : BaseStyleCopIssueSearcher<IFieldElement, IVariableDeclarationStatement> {

        public override IEnumerable<StyleCopIssue> FindFirstIssues(IEnumerable<IElement> elements) {
            var fields = elements.SelectWhereElement<IFieldElement>()
                .Where(f => f.Visibility == MemberVisibility.Private)
                .Where(f => !f.IsReadOnly && !f.IsConst)
                .Cast<IElement>();

            var variables = elements.SelectWhereElement<IVariableDeclarationStatement>().Cast<IElement>();

            return fields.Concat(variables).Where(f => !char.IsLower(f.Name[0]) && char.IsLetter(f.Name[0]))
                .Select(e => new StyleCopIssue {
                Element = e,
                IssueDescription = GetIssueDescription(e)
            });
        }

        private static string GetIssueDescription(IElement element) {
            if (element is IFieldElement) {
                return StyleCop.Resource.FieldNameMustBeginWithLowerCaseLetterFieldIssueDescripton;
            }
            else {
                return StyleCop.Resource.FieldNameMustBeginWithLowerCaseLetterVariableIssueDescripton;
            }
        }
    }
}
